package com.xhwl.centiotdata.suppliersystem.dahuaIcc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.constant.DaHuaIccConstant;
import com.xhwl.centiotdata.pojo.dto.dahua.DeviceDaHuaDTO;
import com.xhwl.centiotdata.pojo.dto.device.DeviceIntegrationConfigDTO;
import com.xhwl.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Service
public class DeviceDaHuaIccHandler {
    private static final Logger log = LoggerFactory.getLogger(DeviceDaHuaIccHandler.class);

    @Autowired
    private GeneralDaHuaIccHandler generalDaHuaIccHandler;

    public List<DeviceDaHuaDTO> pullDevice(DeviceIntegrationConfigDTO configDTO) {

        HashMap<String, Object> params = new HashMap<>();
        params.put("pageNum", 1);
        params.put("pageSize", 500);
        params.put("categorys", new int[]{DaHuaIccConstant.PEDES_DEVICE_TYPE});
        params.put("unitTypes", new int[]{DaHuaIccConstant.PEDES_UNITYPE_DOOR,DaHuaIccConstant.PEDES_UNITYPE_FACE});
        log.info("拉取参数参数:"+params);
        JSONObject resultObject = generalDaHuaIccHandler.post(DaHuaIccConstant.ADMIN_REST_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
//        log.info("拉取设备结果:"+resultObject);
        if (resultObject == null) {
            return null;
        }
        if ("false".equals(resultObject.getString("success"))) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.ADMIN_REST_URL, JSON.toJSONString(params), resultObject.getString("errMsg"));
            return null;
        }
        String dataStr = resultObject.getString("data");
        String pageDataStr = JSON.parseObject(dataStr).getString("pageData");
        if (StringUtils.isEmpty(pageDataStr)) {
            log.error("post path:{};params:{};data is null!", DaHuaIccConstant.ADMIN_REST_URL, JSON.toJSONString(params));
            return null;
        }
        List<DeviceDaHuaDTO> deviceDaHuaDTOList = handleData(pageDataStr);
        if (CollectionUtils.isEmpty(deviceDaHuaDTOList)) {
            return null;
        }
        return deviceDaHuaDTOList;
    }
    private List<DeviceDaHuaDTO> handleData(String pageDataStr) {
        JSONArray arrayObject = JSONObject.parseArray(pageDataStr);
        List<DeviceDaHuaDTO> deviceDaHuaDTOList = new ArrayList<>();
        arrayObject.forEach(object->{
            JSONObject dObject = JSON.parseObject(object.toString());
            JSONObject.parseArray(dObject.getString("units")).forEach(unit->{
                JSONObject unitObject = JSON.parseObject(unit.toString());
                if(StringUtils.equals(DaHuaIccConstant.PEDES_UNITYPE_DOOR.toString(),unitObject.getString("unitType"))){
                    JSONObject.parseArray(unitObject.getString("channels")).forEach(channel->{
                        JSONObject channelObject = JSON.parseObject(channel.toString());
                        DeviceDaHuaDTO deviceDaHuaDTO = new DeviceDaHuaDTO();
                        deviceDaHuaDTO.setDeviceIp(dObject.getString("deviceIp"));
                        if(Integer.parseInt(dObject.getString("isOnline"))>0){
                            deviceDaHuaDTO.setIsDeviceOnline(true);
                        }
                        else{
                            deviceDaHuaDTO.setIsDeviceOnline(false);
                        }
                        deviceDaHuaDTO.setChannelId(channelObject.getString("channelCode"));
                        deviceDaHuaDTO.setChannelName(channelObject.getString("channelName"));
                        deviceDaHuaDTOList.add(deviceDaHuaDTO);
                    });
                }
            });
        });
        return deviceDaHuaDTOList;
    }

    /**
     * 拉取AlarmHost报警主机设备
     *
     * @param configDTO 集成配置业务DTO
     * @return List<DeviceDaHuaDTO>
     */
    public List<DeviceDaHuaDTO> pullAlarmHostDevice(DeviceIntegrationConfigDTO configDTO) {

        HashMap<String, Object> params = new HashMap<>();
        JSONObject resultObject = generalDaHuaIccHandler.post(DaHuaIccConstant.ALARM_HOST_URL, params,
                configDTO.getProjectId(), configDTO.getProductId(),
                configDTO.getIpAndPort(), configDTO.getLoginName(),
                configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (DaHuaIccConstant.FALSE_CODE.equals(resultObject.getString("success"))) {
            log.error("post path:{};errMsg:{}", DaHuaIccConstant.ALARM_HOST_URL, resultObject.getString("errMsg"));
            return new ArrayList<>();
        }

        JSONArray deviceArray = resultObject.getJSONObject("data").getJSONArray("value");
        if (CollectionUtils.isEmpty(deviceArray)) {
            return new ArrayList<>();
        }

        log.info("获取的告警主机信息==>{}", deviceArray);
        List<DeviceDaHuaDTO> alarmHostDeviceList = new ArrayList<>(deviceArray.size());
        deviceArray.forEach(device -> {
            JSONObject jsonObject = (JSONObject) device;
            DeviceDaHuaDTO deviceDaHuaDTO = new DeviceDaHuaDTO();
            deviceDaHuaDTO.setDeviceIp(jsonObject.getString("deviceIp"));
            deviceDaHuaDTO.setChannelId(jsonObject.getString("deviceCode"));
            deviceDaHuaDTO.setChannelName(jsonObject.getString("deviceName"));
            boolean isOnline = !Objects.equals(jsonObject.getInteger("status"), DaHuaIccConstant.ALARM_HOST_OFFLINE);
            deviceDaHuaDTO.setIsDeviceOnline(isOnline);
            alarmHostDeviceList.add(deviceDaHuaDTO);
        });
        return alarmHostDeviceList;
    }
}
